﻿using System.Collections.Specialized;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace FTIOT_CAT1
{
    internal class ConfigurationGeneration
    {
        string intByteLen2 = "var H=\"0x\"+str.slice(6,8);\nvar L=\"0x\"+str.slice(8,10);\nvar b=parseInt(H)*256+parseInt(L);\nif(b>=32768) b=b-65536;\nreturn b";
        string uintByteLen2 = "var H=\"0x\"+str.slice(6,8);\nvar L=\"0x\"+str.slice(8,10);\nvar b=parseInt(H)*256+parseInt(L);\nreturn b";
        string intByteLen4 = "var HH=\"0x\"+str.slice(6,8);\nvar LL = \"0x\" + str.slice(8, 10);\nvar H = \"0x\" + str.slice(10, 12);\nvar L = \"0x\"+ str.slice(12, 14);\n" +
            "var b = parseInt(HH) * 16777216 + parseInt(LL) * 65536 + parseInt(H) * 256 + parseInt(L);\n\\nif(b>=2147483648) b=b-4294967296;\n return b";
        string uintByteLen4 = "var HH=\"0x\"+str.slice(6,8);\nvar LL = \"0x\" + str.slice(8, 10);\nvar H = \"0x\" + str.slice(10, 12);\nvar L = \"0x\"" +
                               "+ str.slice(12, 14);\nvar b = parseInt(HH) * 16777216 + parseInt(LL) * 65536 + parseInt(H) * 256 + parseInt(L);\nreturn b";
        string fd = "var L1=str.slice(6,8);\r\nvar L2=str.slice(8,10);\r\nvar H1=str.slice(10,12);\r\nvar H2=str.slice(12,14);\r\nvar a = \"\"+L1+L2+H1+H2;" +
            "\r\nvar b = parseInt(a,16);\r\nvar s = b&0x80000000/0x80000000;\r\nvar e = (b&0x7f800000)/0x800000-127;\r\nvar c = (b&0x7fffff)/0x800000;" +
            "\r\nvar re = (1+c)*Math.pow(2,e);\r\nreturn re";
        List<string> imgList = new List<string>();
        public ConfigurationGeneration() { TraversePicture(); }

        private void TraversePicture()//遍历img文件夹下的所有图片文件保存文件名到一个列表中
        {
            try
            {
                string[] files = Directory.GetFiles("..//传感器点表\\img", "*.*", SearchOption.AllDirectories)
                                          .Where(s => s.EndsWith(".png") || s.EndsWith(".jpg") || s.EndsWith(".jpeg"))
                                          .ToArray();
                foreach (string file in files)
                {
                    // 只添加文件名，不包含路径
                    string files2 = Path.GetFileName(file); // 获取文件名
                    files2 = files2.Replace(" ", "_"); // 替换空格为下划线
                    imgList.Add(files2); // 只添加文件名
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show("img文件夹打开失败或不存在: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private String GenerateModbusInstruct(byte addr, Int16 regAddr, Int16 dataLen)
        {
            // 生成 Modbus 指令
            byte[] frame = new byte[8];
            UInt16 reg = (UInt16)regAddr;
            frame[0] = addr;
            frame[1] = 0x03;
            frame[2] = (byte)(reg >> 8);
            frame[3] = (byte)(reg & 0xff);
            frame[4] = (byte)(dataLen >> 8); // 高字节
            frame[5] = (byte)(dataLen & 0xff);
            byte[] bytes = new byte[6];
            Array.Copy(frame, 0, bytes, 0, bytes.Length);
            byte[] crc = ModbusUtils.CalculateCRC(bytes);
            frame[6] = crc[0];
            frame[7] = crc[1];
            return BitConverter.ToString(frame).Replace("-", " "); // 返回指令字符串
        }
        private int GetValueTypeNumber(string valueType)
        {
            if (!string.IsNullOrEmpty(valueType) && valueType.Contains('.'))
            {
                var parts = valueType.Split('.');
                int num;
                if (int.TryParse(parts[1], out num))
                    return num;
            }
            return 0;
        }
        private String[] GetDescribeStr(string describe)
        {
            string[] str = new string[2];

            str[0] = describe.Contains(":") ? describe.Split(':')[0] : describe;
            str[1] = describe.Split(':').Length > 1 ? describe.Split(':')[1] : "";
            return str; // 返回冒号前的部分
                        // b0eforeColon 结果为 "气压"
        }
        private String GenerateCmd(int regLen, String valueType, String describe)
        {
            string cmd = "";
            int num = GetValueTypeNumber(valueType);
            if (regLen == 1)
            {
                if (valueType[0] == 'i')
                {
                    cmd = intByteLen2;
                }
                else if (valueType[0] == 'n')
                {
                    cmd = uintByteLen2;
                }

            }
            else if (regLen == 2)
            {
                if (valueType[0] == 'i')
                {
                    cmd = intByteLen4;
                }
                else if (valueType[0] == 'n')
                {
                    cmd = uintByteLen4;
                }
                else if (valueType[0] == 'f')
                {
                    cmd = fd;
                }
            }
            if (num != 0)
            {
                cmd += "/" + Math.Pow(10, num).ToString(); // 处理小数位
            }
            if (describe != "")
            {
                cmd += "+\"" + describe + "\"";

            }

            return cmd + ";";
        }

        string RemoveDigits(string input)
        {
            return Regex.Replace(input, @"\d+", "");
        }
        string? FindExactMatchOrContain(List<string> files, string input)
        {
            string inputNoDigits = RemoveDigits(input);

            // 先找去数字后完全匹配的文件名
            var exactMatch = files.FirstOrDefault(f =>
            {
                string nameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(f);
                string nameNoDigits = RemoveDigits(nameWithoutExt);
                return nameNoDigits == inputNoDigits;
            });

            if (exactMatch != null)
                return exactMatch;

            // 找去数字后包含输入字符串的文件名
            var containsMatch = files.FirstOrDefault(f =>
            {
                string nameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(f);
                string nameNoDigits = RemoveDigits(nameWithoutExt);
                return nameNoDigits.Contains(inputNoDigits);
            });

            if (containsMatch != null)
                return containsMatch;

            // 如果都没找到，再用文件名包含输入（含数字）
            var wholeContainMatch = files.FirstOrDefault(f => f.Contains(input));

            return wholeContainMatch;
        }
        public void JsonTransition(string func, SensorList sensorList)
        {
            SensorModelListModel sensorModel = new();
            // 遍历 JSON 数组并填充 SensorModelListModel
            foreach (var item in sensorList.Sensors)
            {
                String[] describe = GetDescribeStr(item.LEDDisplay);//提取传感器名称和单位
                SensorModel sensor = new SensorModel();
                sensor.name = describe[0]; // 如果没有 name 字段，使用默认值
                sensor.type = func; // 采集的方法类型

                string? imgFileName = FindExactMatchOrContain(imgList, sensor.name);// 查找最匹配的图片文件名
                if (imgFileName == null)
                {
                    imgFileName = "传感器-1.png";
                }
                imgFileName = ".\\img\\" + imgFileName;
                sensor.img = imgFileName;
                sensor.value = "0"; // 默认值，可以根据需要修改

                if (func == "modbus")
                {
                    sensor.cmd = GenerateModbusInstruct((byte)item.DeviceAddress, (Int16)item.RegisterAddress, (Int16)item.RegisterLength);
                    sensor.datProcess = GenerateCmd((int)item.RegisterLength, item.DataType, describe[1]); // 默认数据处理方式，可以根据需要修改
                }
                else if (func == "json")
                {
                    sensor.cmd = item.UploadName;
                    sensor.datProcess = "return str+\"" + describe[1] + "\";"; // 默认数据处理方式，可以根据需要修改
                }
                // 将 Person 对象转换为 SensorModel 对象
                sensorModel.senList.Add(sensor);
            }

            // 输出结果JsonSerializer
            try
            {
                // 配置 JSON 序列化选项（缩进）
                var options = new JsonSerializerOptions
                {
                    WriteIndented = false, // 启用缩进
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping // 可选：避免 Unicode 转义
                };
                // 重新序列化为格式化字符串
                string jsonString = JsonSerializer.Serialize(sensorModel, options);

                string filePath = Path.GetFullPath("cachefile/sensorList.json");
                File.WriteAllText(filePath, jsonString, Encoding.GetEncoding("GBK"));
                StringCollection files = new StringCollection();
                files.Add(filePath);
                Clipboard.SetFileDropList(files);
                // 显示提示信息
                MessageBox.Show("转换完成，结果已保存到 sensorList.json 文件，并复制到剪切板。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (JsonException ex)
            {
                MessageBox.Show("JSON 序列化错误: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
    public class SensorModel
    {
        public string name { get; set; }
        public string type { get; set; }
        public string cmd { get; set; }
        public string img { get; set; }
        public string value { get; set; }
        public string datProcess { get; set; }
    }
    public class SensorModelListModel
    {
        public List<SensorModel> senList { get; set; }
        public SensorModelListModel()
        {
            senList = new();
        }
    }
}


